#include "StdAfx.h"
#include "CodeBookGenerator.h"
#include "cv.h"
#include "highgui.h"

CCodeBookGenerator::CCodeBookGenerator(void)
{
}

CCodeBookGenerator::~CCodeBookGenerator(void)
{
}

CCodeBook* CCodeBookGenerator::CreateCodeBook(CString& sFolder, 
										CFeatureExtract* extractor, CCluster* cluster)
{
	CFileFind finder;
	CArray<CPatchSample*> m_arrFeatures;

	CString sWildcard = sFolder + 
		(sFolder[sFolder.GetLength() - 1] == L'\\' ? L".png" : L"\\*.png");
	BOOL bWorking = finder.FindFile( sWildcard );

	while ( bWorking )
	{
		bWorking = finder.FindNextFile();
		if ( finder.IsDots() || finder.IsDirectory())	// "." and ".." folders
			continue;

		CString sFileName = finder.GetFilePath();
		CArray<double> vecFeature;
		extractor->Calc(sFileName, vecFeature);
		m_arrFeatures.Add(new CPatchSample(sFileName, vecFeature));
	}
	// Cleanup file finder
	finder.Close();
	
	return CreateCodeBook(m_arrFeatures, cluster);
	
}

CCodeBook* CCodeBookGenerator::CreateCodeBook(CArray<CPatchSample*>& m_arrFeatures, CCluster* cluster)
{
	int iSampleCnt = m_arrFeatures.GetCount();
	if(iSampleCnt == 0)
		return NULL;

	CArray<int> clusters;
	if(!cluster->DoCluster(m_arrFeatures, clusters))
		return NULL;

	ASSERT(clusters.GetCount() == iSampleCnt);

	CCodeBook* codeBook = new CCodeBook();
	for(int i = iSampleCnt - 1; i >= 0; --i)
	{
		int iCluster = clusters[i];
		while(codeBook->Entries.GetCount() <= iCluster)
		{
			codeBook->Entries.Add(new CCodeBookEntry());
		}
		CCodeBookEntry* entry = codeBook->Entries.GetAt(iCluster);
		entry->Words.Add(m_arrFeatures[i]);
	}
	codeBook->FindReprestantives();
	return codeBook;
}